package com.yunchao.library.socket

import android.annotation.SuppressLint

import com.yunchao.library.socket.constants.Values
import com.yunchao.library.socket.model.connection.AccessRequest
import com.yunchao.library.socket.model.connection.EnvironmentCheck
import com.yunchao.library.socket.model.connection.HardwareDescriptor
import com.yunchao.library.socket.model.control.ConfirmRequest
import com.yunchao.library.socket.model.control.DispatchRequest
import com.yunchao.library.socket.model.control.ExecuteRequest
import com.yunchao.library.socket.model.error.ErrorFeedback
import com.yunchao.library.socket.model.metadata.MetadataSyncRequest
import com.yunchao.library.socket.model.power.PowerManagement
import com.yunchao.library.socket.model.response.AccessResponse
import com.yunchao.library.socket.model.response.AuthorizationResponse
import com.yunchao.library.socket.model.response.ConfirmResponse
import com.yunchao.library.socket.model.response.DataExchangeResponse
import com.yunchao.library.socket.model.response.DispatchResponse
import com.yunchao.library.socket.model.response.EnvironmentCheckResponse
import com.yunchao.library.socket.model.response.ExecuteResponse
import com.yunchao.library.socket.model.response.MetadataSyncResponse
import com.yunchao.library.socket.model.response.SubmitResponse
import com.yunchao.library.socket.model.security.AutographData
import com.yunchao.library.socket.model.security.DataExchange
import com.yunchao.library.socket.model.security.SecuritySession
import com.yunchao.library.socket.model.submit.AuthorRequest
import com.yunchao.library.socket.model.submit.SubmitRequest
import timber.log.Timber
import java.time.Instant

/**
 * Socket通信协议主入口点
 *
 * 提供所有请求和响应的工厂方法，以及协议相关常量和工具方法
 *
 */
object SocketProtocol {
    // ====================== 连接管理 ======================

    /**
     * 创建硬件描述符
     */
    private fun createHardwareDescriptor(
        id: String,
        version: String,
        token: Int = Values.DEFAULT_TOKEN,
        prefix: String = "yunchao",
        provider: String = "yunchao",
        label: String = "shouchi",
        model: String = "YC-SeuicPDA",
        heartbeat: Int = Values.DEFAULT_HEARTBEAT
    ): HardwareDescriptor {
        return HardwareDescriptor(
            id = id,
            version = version,
            token = token,
            prefix = prefix,
            provider = provider,
            label = label,
            model = model,
            heartbeat = heartbeat
        ).also {
            Timber.d("创建硬件描述符: $it")
        }
    }

    /**
     * 创建接入请求
     */
    fun createAccessRequest(bytes: ByteArray): AccessRequest =
        AccessRequest.fromByteArray(bytes).also {
            Timber.d("创建接入请求: $it")
        }

    /**
     * 创建环境检查请求
     */
    fun createEnvironmentCheck(bytes: ByteArray): EnvironmentCheck =
        EnvironmentCheck.fromByteArray(bytes).also {
            Timber.d("创建环境检查请求: $it")
        }

    // ====================== 控制指令 ======================

    /**
     * 创建调度请求
     */
    fun createDispatchRequest(bytes: ByteArray): DispatchRequest =
        DispatchRequest.fromByteArray(bytes).also {
            Timber.d("创建任务下发请求 : $it")
        }

    /**
     * 创建执行请求
     */
    fun createExecuteRequest(bytes: ByteArray): ExecuteRequest =
        ExecuteRequest.fromByteArray(bytes).also {
            Timber.d("创建执行请求 : $it")
        }

    /**
     * 创建确认请求
     */
    fun createConfirmRequest(bytes: ByteArray): ConfirmRequest =
        ConfirmRequest.fromByteArray(bytes).also {
            Timber.d("创建确认请求 : $it")
        }

    // ====================== 数据提交 ======================

    /**
     * 创建提交请求
     *   id: Int,
     *             fragment: Int = 0,
     *             timestamp: Long,
     *             data: String,
     *             operator: Int = 0,
     *             auditor: Int = 0
     */
    fun createSubmitRequest(
        id: UInt,
        fragment: UInt = 0u,
        @SuppressLint("NewApi") timestamp: ULong = Instant.now().toEpochMilli().toULong(),
        data: String,
        operator: UInt = 0u,
        auditor: UInt = 0u
    ): SubmitRequest = SubmitRequest(id, fragment, timestamp, data, operator, auditor).also {
        Timber.d("创建提交请求 : $it")
    }

    /**
     * 创建授权请求
     */
    fun createAuthorizationRequest(aid: String, users: List<UInt>): AuthorRequest =
        AuthorRequest(aid, users).also {
            Timber.d("创建授权请求 : $it")
        }

    // ====================== 元数据同步 ======================

    /**
     * 创建元数据同步请求
     */
    fun createMetadataSyncRequest(bytes: ByteArray): MetadataSyncRequest =
        MetadataSyncRequest.fromByteArray(bytes).also {
            Timber.d("创建元数据同步请求 : $it")
        }

    // ====================== 安全令牌 ======================

    /**
     * 创建电源管理Payload
     */
    fun createPowerManagementPayload(bytes: ByteArray): PowerManagement.Payload =
        PowerManagement.Payload.fromByteArray(bytes).also {
            Timber.d("创建电源管理 : $it")
        }

    /**
     * 创建数据交换请求
     */
    fun createDataExchange(bytes: ByteArray): DataExchange =
        DataExchange.fromByteArray(bytes).also {
            Timber.d("创建数据交换请求 : $it")
        }

    fun createAutographData(bytes: ByteArray): AutographData =
        AutographData.fromByteArray(bytes).also {
            Timber.d("创建数据交换Handle == 1 请求 : $it")
        }

    // ====================== 安全会话 ======================


    /**
     * 创建安全会话
     */
    fun createSecuritySession(bytes: ByteArray): SecuritySession =
        SecuritySession.fromByteArray(bytes).also {
            Timber.d("创建安全会话 : $it")
        }

    // ====================== 错误处理 ======================

    /**
     * 创建错误反馈
     */
    fun createErrorFeedback(bytes: ByteArray): ErrorFeedback =
        ErrorFeedback.fromByteArray(bytes).also {
            Timber.d("创建错误反馈 : $it")
        }

    // ====================== 响应对象 ======================

    fun createDispatchResponse(error: String = "") = DispatchResponse(error).toByteArray()
    fun createExecuteResponse(error: String = "") = ExecuteResponse(error).toByteArray()
    fun createConfirmResponse(error: String = "") = ConfirmResponse(error).toByteArray()
    fun createMetadataSyncResponse(error: String = "") = MetadataSyncResponse(error).toByteArray()
    fun createSubmitResponse(error: String = "") = SubmitResponse(error).toByteArray()
    fun createAuthorResponse(error: String = "") = AuthorizationResponse(error).toByteArray()
    fun createEnvironmentCheckResponse(error: String = "") =
        EnvironmentCheckResponse(error).toByteArray()

    fun createAccessResponse(error: String = "") = AccessResponse(error).toByteArray()


    fun createDataExchangeResponse(errorMessage: String? = null, rApdu: ByteArray): ByteArray {
        return errorMessage?.let { DataExchangeResponse.failure(it).toByteArray() }
            ?: DataExchangeResponse.success(rApdu).toByteArray()
    }

    /**
     * 生成默认硬件描述符
     */
    fun generateDefaultHardwareDescriptor(
        deviceId: String,
        firmwareVersion: String
    ): HardwareDescriptor {
        return createHardwareDescriptor(
            id = deviceId,
            version = firmwareVersion
        )
    }
}